package br.com.salao.session;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import br.com.salao.ejb.dao.LoginDao;
import br.com.salao.ejb.dao.impl.LoginDaoImpl;
import br.com.salao.ejb.security.Criptografia;
import br.com.salao.entity.Login;

@Stateless
@Remote(LoginBase.class)
public class LoginBean implements LoginBase {

	/**
	 * @author: Adriana
	 */
	private static final long serialVersionUID = 1L;

	private Logger logger = Logger.getLogger(LoginBean.class.getName());

	@PersistenceContext(unitName = "SalaoBeleza")
	private EntityManager em;
	
	private Login loginAcesso;

	public LoginBean(){
		//	em = JpaUtil.getEntityManager();
		loginAcesso = new Login();
	}

	@PostConstruct
	public void initialize () {
		System.out.println("LoginBean initialized.");
	}

	@TransactionAttribute
	public Login inserir(Login login) throws NoSuchAlgorithmException, UnsupportedEncodingException, Exception{

		LoginDao dao = new LoginDaoImpl(em);
		try{		
			Criptografia criptografia = new Criptografia();
			String senhaCriptografada = criptografia.gerarSenhaCriptografada(login.getSenha());
			login.setSenha(senhaCriptografada);
		}catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getStackTrace() + "\n");
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");

			logger.error(sb.toString());

			e.printStackTrace();
			
			throw e;
		}
		return dao.inserir(login);
	}

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public Login buscarLoginPorDescricao(Login login) throws Exception{
		logger.debug(":: LoginBean :: buscarLoginPorDescricao :: " + login.getLogin() );
		LoginDao dao = new LoginDaoImpl(em);
		return dao.buscarLoginPorDescricao(login.getLogin());
	}

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public Login buscarLoginPorId(int id){
		LoginDaoImpl dao = new LoginDaoImpl(em);
		return dao.buscarLoginPorId(id);
	}

	@TransactionAttribute
	public Login update(Login login)throws Exception {
		LoginDao dao = new LoginDaoImpl(em);
		return dao.update(login);
	}

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public Login buscarLoginPorDescricao(String login) throws Exception {
		logger.debug(":: LoginBean :: buscarLoginPorDescricao :: " + login);
		LoginDao dao = new LoginDaoImpl(em);
		return dao.buscarLoginPorDescricao(login);
	}

	public Login getLoginAcesso() {
		return loginAcesso;
	}

	public void setLoginAcesso(Login loginAcesso) {
		this.loginAcesso = loginAcesso;
	}

}
